import path from 'path';
import fs from 'fs-extra';
import inquirer from 'inquirer';
import { execa } from 'execa';
import { blue, green, red } from 'kolorist';
import { getTemplateDir, isEmpty, emptyDir, copyTemplate } from './utils.js';
import { 
  getProjectName, 
  getFeaturePrompts, 
  getOverwritePrompt, 
  displayFeatureSummary,
  getFinalConfirmation
} from './prompts.js';

// 默认配置
const DEFAULT_FEATURES = {
  typescript: false,
  jsx: false,
  router: false,
  pinia: false,
  vitest: false,
  eslint: false
};

// 生成package.json
const generatePackageJson = (projectName, features) => {
  const dependencies = {
    "vue": "^3.4.0"
  };
  
  const devDependencies = {
    "@vitejs/plugin-vue": "^5.0.4",
    "vite": "^5.1.6"
  };
  
  // 添加特性相关依赖
  if (features.typescript) {
    devDependencies["typescript"] = "^5.0.2";
    devDependencies["vue-tsc"] = "^2.0.16";
  }
  
  if (features.router) {
    dependencies["vue-router"] = "^4.3.0";
  }
  
  if (features.pinia) {
    dependencies["pinia"] = "^2.1.7";
  }
  
  if (features.vitest) {
    devDependencies["vitest"] = "^1.4.0";
    devDependencies["@vue/test-utils"] = "^2.4.5";
  }
  
  if (features.eslint) {
    devDependencies["eslint"] = "^8.57.0";
    devDependencies["eslint-plugin-vue"] = "^9.25.0";
  }
  
  return {
    name: projectName,
    version: "0.1.0",
    private: true,
    scripts: {
      dev: "vite",
      build: "vite build",
      preview: "vite preview",
      ...(features.vitest ? { test: "vitest" } : {})
    },
    dependencies,
    devDependencies
  };
};

// 创建项目
export const create = async (projectName = 'my-project', options) => {
  const cwd = process.cwd();
  let targetDir = projectName || '.';
  const root = path.resolve(cwd, targetDir);
  
  // 检查目录是否存在
  if (fs.existsSync(root) && !options.force) {
    if (!isEmpty(root)) {
      const { shouldOverwrite } = await inquirer.prompt([
        getOverwritePrompt().message(`Target directory "${targetDir}" is not empty.`)
      ]);
      
      if (shouldOverwrite) {
        emptyDir(root);
      } else {
        console.log(red('✘ Operation cancelled'));
        return;
      }
    }
  } else {
    fs.mkdirSync(root, { recursive: true });
  }
  
  // 获取项目配置
  let features = { ...DEFAULT_FEATURES };
  
  if (options.default) {
    console.log(blue('ℹ Using default configuration'));
  } else {
    if (!projectName) {
      targetDir = await getProjectName();
    }
    
    features = await inquirer.prompt(getFeaturePrompts());
    displayFeatureSummary(features);
    
    const { confirm } = await inquirer.prompt([getFinalConfirmation()]);
    if (!confirm) {
      console.log(red('✘ Operation cancelled'));
      return;
    }
  }
  
  // 创建项目目录
  console.log();
  console.log(blue(`Creating project in ${green(root)}`));
  
  // 复制基础模板
  const templateDir = getTemplateDir('base');
  copyTemplate(templateDir, root, {
    projectName: targetDir
  });
  
  // 添加特性模板
  const featureTemplates = {
    typescript: 'ts',
    router: 'router',
    pinia: 'pinia',
    vitest: 'vitest',
    eslint: 'eslint'
  };
  
  for (const [feature, template] of Object.entries(featureTemplates)) {
    if (features[feature]) {
      const featureDir = getTemplateDir(template);
      copyTemplate(featureDir, root);
    }
  }
  
  // 生成package.json
  const pkg = generatePackageJson(targetDir, features);
  fs.writeFileSync(
    path.resolve(root, 'package.json'),
    JSON.stringify(pkg, null, 2)
  );
  
  // 初始化Git仓库
  const gitInit = async () => {
    try {
      await execa('git', ['init'], { cwd: root });
      console.log(green('✔ Git repository initialized'));
    } catch (e) {
      console.log(yellow('⚠ Git initialization failed'));
    }
  };
  
  // 安装依赖
  const installDependencies = async () => {
    console.log(blue('\nInstalling dependencies...'));
    try {
      await execa('npm', ['install'], { 
        cwd: root,
        stdio: 'inherit'
      });
      console.log(green('✔ Dependencies installed'));
    } catch (e) {
      console.log(red('✘ Dependency installation failed'));
    }
  };
  
  await gitInit();
  await installDependencies();
  
  // 完成提示
  console.log();
  console.log(green('🎉 Project created successfully!'));
  console.log();
  
  if (root !== cwd) {
    console.log(`  cd ${blue(targetDir)}`);
  }
  
  console.log(`  ${blue('npm run dev')} - start development server`);
  
  if (features.vitest) {
    console.log(`  ${blue('npm run test')} - run unit tests`);
  }
  
  console.log();
};